package com.cn.steam.foundation.common.web.config.jwt;

import com.cn.steam.foundation.common.model.ExceptionResponse;
import com.cn.steam.foundation.common.utils.JsonUtils;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author huangzz
 */

/**
 * AuthenticationEntryPoint是Spring Security Web一个概念模型接口，顾名思义，他所建模的概念是:“认证入口点”。
 * 它在用户请求处理过程中遇到认证异常时，被ExceptionTranslationFilter用于开启特定认证方案(authentication schema)的认证流程。
 * https://blog.csdn.net/andy_zhang2007/article/details/91355520
 */
public class CommonAuthenticationEntryPoint implements AuthenticationEntryPoint {
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
		ExceptionResponse exceptionResponse = new ExceptionResponse(Integer.toString(HttpServletResponse.SC_UNAUTHORIZED), authException.getMessage());
		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		response.setCharacterEncoding("utf-8");
		response.setContentType(MediaType.APPLICATION_JSON_VALUE);
		PrintWriter printWriter = response.getWriter();
		printWriter.print(JsonUtils.toJsonString(exceptionResponse));
		printWriter.flush();
		printWriter.close();
	}
}